package com.heima.behavior.service.impl;

import com.heima.behavior.dto.ReadBehaviorDto;
import com.heima.behavior.entity.ApReadBehavior;
import com.heima.behavior.service.IApReadBehaviorService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author 20929
 */
@Service
public class IApReadBehaviorServiceImpl implements IApReadBehaviorService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult saveRead(ReadBehaviorDto dto) {
        if (dto == null || dto.getEquipmentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //用户id
        User user = AppThreadLocalUtil.get();
        if (user == null || user.getUserId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //文章id
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Query query = new Query(
                Criteria.where("entryId").is(user.getUserId()).and("articleId").is(dto.getArticleId())
        );
        ApReadBehavior one = mongoTemplate.findOne(query, ApReadBehavior.class);
        if (one == null) {
            one = new ApReadBehavior();
            BeanUtils.copyProperties(dto, one);
            one.setEntryId(user.getUserId());
            one.setCreatedTime(new Date());
            one.setUpdatedTime(new Date());
            mongoTemplate.save(one);
        } else {
            BeanUtils.copyProperties(dto, one);
            one.setCount(one.getCount() + 1);
            one.setUpdatedTime(new Date());
            mongoTemplate.save(one);
        }
        return ResponseResult.okResult();
    }
}
